package com.wzqj.agent.app.merchant.controller;

import com.alibaba.fastjson.JSONObject;
import com.wzqj.agent.app.login.controller.AuthRequiredController;
import com.wzqj.agent.app.merchant.service.ApiMerchantService;
import com.wzqj.agent.app.user.domain.UserInfo;
import com.wzqj.agent.app.user.service.ApiUserService;
import com.wzqj.agent.common.JsonOutput;
import com.wzqj.agent.common.exception.BusinessErrorType;
import com.wzqj.agent.common.exception.BusinessException;
import com.wzqj.agent.common.redis.CacheClient;
import com.wzqj.agent.common.redis.CacheKey;
import com.wzqj.agent.util.CaptchaUtil;
import com.wzqj.agent.util.SmsSOA;
import com.wzqj.agent.util.ValidateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by wanghao@weipass.cn on 2015/7/28.
 */
@Controller
@RequestMapping("/api/merchant")
public class ApiMerchantController extends AuthRequiredController{

    @Autowired
    private CacheClient cacheClient;

    @Autowired
    private ApiMerchantService apiMerchantService;

    @Autowired
    private ApiUserService apiUserService;

    /**
     * 判断商户是否存在不存在则注册商户,返回商户资质
     * @param mobile
     * @param captcha
     * @param passlen
     * @return
     */
    @RequestMapping("/register")
    @ResponseBody
    public JSONObject register(HttpServletRequest req,String mobile,String captcha,int passlen){

        String wid = req.getParameter("wid");
        JsonOutput output = new JsonOutput();
        if(!ValidateUtil.isMobile(mobile) || !ValidateUtil.isCaptcha(captcha)){
            output.setErrCode(BusinessErrorType.PARAM_ERROR.getErrCode());
            output.setMsg(BusinessErrorType.PARAM_ERROR.getErrMsg());
            return output.toJSONObject();
        }
        /**
         * 校验手机验证码是否正确
         */
        Object captchaCache = cacheClient.get(CacheKey.用户登录验证码 + mobile);
        if(null == captchaCache){//验证码已过期
            output.setErrCode(BusinessErrorType.LOGIN_CAPTCHA_INVALID.getErrCode());
            output.setMsg(BusinessErrorType.LOGIN_CAPTCHA_INVALID.getErrMsg());
        }else if(!captchaCache.equals(captcha)){//验证码不正确
            output.setErrCode(BusinessErrorType.LOGIN_CAPTCHA_ERROR.getErrCode());
            output.setMsg(BusinessErrorType.LOGIN_CAPTCHA_ERROR.getErrMsg());
        }else{//验证通过,查询或创建商户
            JSONObject data = new JSONObject();
            try {
                JSONObject merchant = apiMerchantService.getMerchant(mobile);
                if( merchant != null ){//商户存在获取商户资质信息
                    String id = merchant.getString("merId");
                    String uid = merchant.getString("id");
                    String nickname = merchant.getString("nickname");
                    if(StringUtils.isEmpty(id)){//用户没有资质认证
                    	
                        id = apiMerchantService.addQualification(mobile, uid);
                    }
                    UserInfo userInfo = apiUserService.getUserInfo(wid);
                    apiUserService.bindMerchantToUserNew(id, userInfo.getUserId());
                    
                    data.put("uid",uid);
                    data.put("nickname",nickname);
                    data.put("qualification",id);
                } else {//商户不存在注册商户并进行资质认证发送密码给商户
                    /**
                     * 生成随机密码发送给用户
                     */
                    String password = CaptchaUtil.generatPassword(passlen == 0 ? 6 : passlen);
                    merchant = apiMerchantService.register(mobile, password);
                    if(merchant != null && !merchant.isEmpty()){
                        String uid = merchant.getString("id");
                        String nickname = merchant.getString("nickname");
                        StringBuffer buffer = new StringBuffer();
                        buffer.append("【微智全景】 您的商户平台登录密码是：").append(password);
                        SmsSOA.sendSms(mobile, buffer.toString());
                        String qualificationid = apiMerchantService.addQualification(mobile, uid);
                        data.put("uid",uid);
                        data.put("nickname",nickname);
                        data.put("qualification",qualificationid);
                        UserInfo userInfo = apiUserService.getUserInfo(wid);
                        apiUserService.bindMerchantToUser(qualificationid, userInfo.getUserId());
                    }else{//用户注册失败
                        output.setErrCode(BusinessErrorType.MERCHANT_REGISTER_ERROR.getErrCode());
                        output.setMsg(BusinessErrorType.MERCHANT_REGISTER_ERROR.getErrMsg());
                    }
                }
                output.setData(data);
            } catch (BusinessException e) {
                output.setErrCode(e.getErrCode());
                output.setRetCode(e.getInnerErrCode());
                output.setMsg(e.getErrMsg());
            }
        }
        return output.toJSONObject();
    }

}
